#include <iostream>
#include <fstream>
#include "contacts.pb.h"

using namespace contacts;

void PrintContacts(contacts::contacts& con)
{
    for(int i= 0; i < con.peo_size();i++)
    {
        std::cout << "---------------联系人" << i+1 << "---------------" << std::endl;
        const contacts::PeopleInof& people = con.peo(i);
        std::cout << "联系人姓名:" << people.name() << std::endl;
        std::cout << "联系人年龄:" << people.age() << std::endl;
        for(int j = 0;j <people.phone_size();j++)
        {
            const ::contacts::Phone& phone = people.phone(j);
            std::cout << "联系人电话:" << j+1 << ":" << phone.number();
            //添加联系人电话类型
            //static inline const std::string& PhoneType_Name(T enum_t_value)也就是设置类型
            std::cout << "  (" << phone.PhoneType_Name(phone.type()) << ")" << std::endl;
        }
        //打印联系人地址信息
        //先判断是由有该信息
        //has_data()表示的是我们是否有对data字段设值(也就是我们write中的mutable_data()函数)
        //并且判断其类型是不是我们的的地址类型(Address)
        if(people.has_data() && people.data().Is<contacts::Address>())
        {
            contacts::Address address;
            //UnpackTo()表示的就是将我们的Any-->Address
            people.data().UnpackTo(&address);
            if(!address.home_address().empty())//判断其家庭地址是否为空
                std::cout << "联系人家庭地址:" << address.home_address() << std::endl;
            if(!address.unit_address().empty())//判断其单位地址是否为空
                std::cout << "联系人单位地址:" << address.unit_address() << std::endl;
        }
        //打印其他联系方式
        switch(people.other_contact_case())
        {
            case contacts::PeopleInof::OtherContactCase::kQq:
                std::cout << "QQ:" << people.qq() << std::endl;
                break;
            case contacts::PeopleInof::OtherContactCase::kWechat:
                std::cout << "WeChat:" << people.wechat() << std::endl;
                break;
            default:
                break;
        }

        //打印备注信息
        if(people.remake_size())
        {
            std::cout << "备注信息:" << std::endl;
        }
        for(auto it = people.remake().cbegin(); it != people.remake().cend();it++)
        {
            std::cout << it->first << " : " << it->second << std::endl;
        }
    }
}

int main()
{
    contacts::contacts contacts1;
    //读取本地全部已经存在的通讯录文件
    std::fstream out("contacts.bin",std::ios::in | std::ios::binary);
    //ParseFromIstream()函数(反序列化)也就是判断是不是反序列化成功
    if(!contacts1.ParseFromIstream(&out))
    {
        std::cerr << "parse error!" << std::endl;
        out.close();
        return -1;
    }
    //打印该通讯录中的所有联系人
    PrintContacts(contacts1);
    return 0;
}